<template>
  <div>
    <el-form ref="assetForm" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row :gutter="40">
        <el-col :span="24">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formItem.name" placeholder="名称" :maxlength="255" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="阈值(个数)" required prop="amount">
            <el-input-number v-model="formItem.amount" :min="1" :max="999999" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24">
          <el-form-item label="通知人" prop="users">
            <el-input placeholder="请选择通知人" @focus="handleUserClick" />
            <div v-if="formItem.users.length > 0" class="fix-input-prefix2">
              <el-tag v-for="tag in formItem.users" :key="tag.name" size="mini" closable type="success" @close="removeUser(tag)">{{ tag.name }}</el-tag>
              <i class="el-icon-close" title="清除所有值" @click="clearAllUser" />
            </div>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="资产类型" required prop="assetTypeCodes">
            <treeselect
              v-model="formItem.assetTypeCodes"
              :multiple="true"
              :options="typeOptions"
              placeholder="选择资产类型"
              value-consists-of="LEAF_PRIORITY"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="通知类型" prop="noticeType">
            <el-select v-model="formItem.noticeType" class="select_input" multiple placeholder="请选择通知类型">
              <el-option v-for="(item) in notices" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="formItem.note" placeholder="请输入备注" :maxlength="1023" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <SelectDialog title="选择通知人" :append-to-body="true" :show="userSelDialogFormVisible" @on-ok="selectUserOk" @on-cancel="selectUserCancel">
      <UsersPage ref="usersSel" :for-selection="true" :multiple-selected="true" :role-code-array="roleCodeArray" />
    </SelectDialog>
  </div>
</template>

<script>
import { tree } from '@neu/dcam-ui/api/assetType'
import UsersPage from '@neu/auth-ui/views/users/tables'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import { create, update, detail } from '@neu/dcam-ui/api/stockwarning'
import { SL_ROLES } from '@neu/dcam-ui/utils/constants'
// 定义一个表单原始项
const formItem = {
  name: '',
  amount: '',
  users: [],
  // userIds: '',
  // userName: [],
  // assetTypeName: [],
  // assetTypeIds: [],
  assetTypeCodes: [],
  // assetTypes: [],
  note: '',
  noticeType: []
}
export default {
  name: 'StockwarningEditForm',
  components: {
    UsersPage,
    SelectDialog
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },

  data() {
    return {
      roleCodeArray: Object.keys(SL_ROLES).join(','),
      // notices: [{ value: 'message', label: '短信' }, { value: 'email', label: '邮件' }, { value: 'notice', label: '系统通知' }],
      notices: [{ value: 'notice', label: '系统通知' }],
      /** 是否显示维保负责人的数据 */
      userSelDialogFormVisible: false,
      /** 供应商信息对话框是否显示 */
      manucacturerSelect: false,
      formItem: { ...formItem },
      /** 资产类型树 */
      typeOptions: [],
      // 表单验证规则
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        users: [{ required: true, type: 'array', message: '通知人不能为空', trigger: 'change' }],
        assetTypeCodes: [{ required: true, type: 'array', message: '选择资产类型', trigger: 'change' }],
        noticeType: [{ required: true, type: 'array', message: '通知类型不能为空', trigger: 'blur' }]

      }
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler() {
        if (this.id) {
          this.fetch()
        }
      },
      immediate: true
    }
  },
  created() {
    tree('sl', '3').then(response => {
      const result = response.data
      this.typeOptions = result
    })
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.formItem = { ... response.data }
          if (this.formItem.contract === null) {
            this.formItem.contract = {}
          }
        })
      } else {
        this.formItem = { ...formItem }
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.assetForm.validate((valid) => {
          if (valid) {
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.assetForm.resetFields()
      formItem.users = []
      // formItem.userName = []
      formItem.assetTypeCodes = []
      formItem.noticeType = []
      this.formItem = { ...formItem }
    },

    /** 选择通知人 */
    handleUserClick() {
      this.userSelDialogFormVisible = true
    },
    selectUserOk() {
      const self = this
      var users = this.$refs.usersSel.selections
      var currentUserIds = self.formItem.users.map(user => user.businessId)
      var difference = users.filter(t => {
        return !currentUserIds.includes(t.username)
      })
      difference.forEach(t => {
        const user = { businessId: t.username + '', name: t.name }
        self.formItem.users.push(user)
      })

      this.userSelDialogFormVisible = false
    },
    selectUserCancel() {
      this.userSelDialogFormVisible = false
    },
    /** 删除某一项 */
    removeUser(tag) {
      this.formItem.users.splice(this.formItem.users.indexOf(tag), 1)
    },
    /** 删除所有项 */
    clearAllUser() {
      this.formItem.users = []
    }
  }
}
</script>
